package com.wang.transfer.util.algorithm;

/**
 * N字形变换
 */
public class NConvert {

    public static void main(String[] args) {
        String s = "PAYPALISHIRING";
        String s1 = new NConvert().nConvert(s, 3);
        System.out.println(s1);
    }

    public String nConvert(String s, int numRows) {
        // 处理只给一行的情况
        if (numRows == 1) {
            return s;
        }
        int sl = s.length();
        int line = sl / 2;
        line = sl % 2 == 0 ? line : line + 1;
        char[][] chars = new char[numRows][line];
        int j = 0, n = 0;
        boolean tag = true;
        for (int i = 0; ; i++) {
            if (sl == n) {
                break;
            }
            if (!tag && j >= 0) {
                chars[j][i] = s.charAt(n++);
                if (j == 0) {
                    ++j;
                    --i;
                    tag = true;
                } else {
                    --j;
                }
                continue;
            }
            while (j <= numRows && tag) {
                chars[j][i] = s.charAt(n++);
                if (j == numRows - 1) {
                    tag = false;
                    --j;
                    break;
                } else {
                    ++j;
                }
                if (n == sl) {
                    break;
                }
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (char[] aChar : chars) {
            for (char c : aChar) {
                if (c == 0) {
                    continue;
                }
                stringBuilder.append(c);
            }
        }
        return stringBuilder.toString();
    }
}
